<template>
  <div class="addtalk">
    <div class="top-title"  @click="go_back">
      <div class="top_left">
        <van-icon name="arrow-left"/>
      </div>
      <div class="top_second">
        {{ title }}
      </div>
      <div class="top_right" @click="submit">
        <van-button class="submit_button" type="info" :loading="submitting">{{ submitting ? '发布中...' : '发布' }}</van-button>
      </div>
    </div>
    <van-notice-bar scrollable left-icon="volume">
      温馨提示：发布请注意文明用语！良言一句三冬暖，恶语伤人六月寒！
    </van-notice-bar>

    <div class="achievement-container">
      <div class="addtalk_nr_big">
        <van-cell-group>
          <van-field
              type="textarea"
              v-model="talk_title"
              label="标题"
              placeholder="请输入标题"
              rows="2"
              autosize
              required
              :rules="[{ required: true, message: '请填写标题' }]"
          />
        </van-cell-group>

        <van-cell-group>
          <van-field
              type="textarea"
              v-model="talk_nr"
              label="内容"
              placeholder="请输入内容"
              rows="4"
              autosize
              maxlength="50"
              show-word-limit
              :rules="[{ required: true, message: '请填写内容' }]"
          />
        </van-cell-group>

        <div class="upload-section">
          <div class="upload-title">上传图片</div>
          <van-uploader
              v-model="fileList"
              multiple
              :max-count="5"
              :after-read="afterReadFile"
              class="uploader"
          >
            <template #preview-cover="{ file }">
              <div class="preview-cover">
                <div v-if="file.status === 'uploading'" class="upload-status uploading">
                  上传中...
                </div>
                <div v-if="file.status === 'failed'" class="upload-status failed">
                  上传失败
                </div>
                {{ file.name }}
              </div>
            </template>
          </van-uploader>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useRoute } from 'vue-router';
import router from "../../Router";
import { uploadUsingPost } from '../../Api/wenjianshangchuanmokuai.ts'
import { addTeachingPostUsingPost } from '../../Api/jiaoshimokuai.ts'
import { showFailToast, showSuccessToast, showConfirmDialog } from "vant";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo.ts'

const route = useRoute();
const userInfo = useUserStore();

// 状态
const submitting = ref(false)

// 表单数据
const title = computed(() => route.meta.title || '发布教学帖子');
const talk_title = ref("")
const talk_nr = ref("")
const relatedCourse = ref("") // 相关课程信息
const fileList = ref<Array<{file?: File, url?: string, name?: string, status?: string, message?: string}>>([])
const photoList = ref<Array<{file?: File, url?: string, name?: string, status?: string, message?: string}>>([])

// 上传图片处理
const afterReadPhoto = async (file: any) => {
  await handleFileUpload(file, photoList)
}

// 上传文件处理
const afterReadFile = async (file: any) => {
  await handleFileUpload(file, fileList)
}

// 通用文件上传处理
const handleFileUpload = async (file: any, targetList: any) => {
  try {
    const files = Array.isArray(file) ? file : [file]

    for (const f of files) {
      f.status = 'uploading'
      f.message = '上传中...'

      // 检查文件大小
      if (f.file && f.file.size > 10 * 1024 * 1024) {
        throw new Error(`文件 ${f.file.name} 大小超过10MB限制`)
      }

      // 上传文件
      const response = await uploadFile(f)
      if (response) {
        f.status = 'done'
        f.url = response
        f.message = '上传成功'
      } else {
        throw new Error('上传失败')
      }
    }
  } catch (error: any) {
    file.status = 'failed'
    file.message = error.message || '上传失败'
    showFailToast(file.message)
  }
}

// 上传单个文件
const uploadFile = async (fileItem: { file?: File }, retries = 3) => {
  if (!fileItem.file) throw new Error('无效的文件')

  let lastError

  for (let i = 0; i < retries; i++) {
    try {
      const response = await uploadUsingPost({}, fileItem.file)

      if (response.data.code === 0 && response.data.data) {
        return response.data.data
      } else {
        lastError = new Error(response.data.message || '文件上传失败')
      }
    } catch (error) {
      lastError = error
    }

    if (i < retries - 1) {
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }

  throw lastError
}

// 表单验证
const validateForm = () => {
  if (!talk_title.value.trim()) {
    showFailToast('请填写标题')
    return false
  }

  if (!talk_nr.value.trim()) {
    showFailToast('请填写内容')
    return false
  }

  // if (!relatedCourse.value.trim()) {
  //   showFailToast('请填写相关课程信息')
  //   return false
  // }

  return true
}

// 提交表单
async function submit() {
  if (!validateForm()) return

  try {
    submitting.value = true

    // 1. 上传所有图片
    let photoUrls: string[] = []
    if (photoList.value.length > 0) {
      showSuccessToast('正在上传图片...')
      const uploadPromises = photoList.value
          .filter(file => file.file && !file.url)
          .map(file => uploadFile(file))

      try {
        const uploadedUrls = await Promise.all(uploadPromises)
        photoUrls = [...uploadedUrls, ...photoList.value.filter(f => f.url).map(f => f.url as string)]
      } catch (error) {
        console.error('图片上传失败:', error)
        throw new Error('图片上传失败，请重试')
      }
    }

    // 2. 上传所有文件
    let fileUrls: string[] = []
    if (fileList.value.length > 0) {
      showSuccessToast('正在上传资源...')
      const uploadPromises = fileList.value
          .filter(file => file.file && !file.url)
          .map(file => uploadFile(file))

      try {
        const uploadedUrls = await Promise.all(uploadPromises)
        fileUrls = [...uploadedUrls, ...fileList.value.filter(f => f.url).map(f => f.url as string)]
      } catch (error) {
        console.error('资源上传失败:', error)
        throw new Error('资源上传失败，请重试')
      }
    }

    // 3. 准备提交数据 - 根据TeachingPostRequest接口
    const submitData = {
      title: talk_title.value.trim(),
      content: talk_nr.value.trim(),
      authorId: userInfo.userInfo.userId, // 从用户store获取
      relatedCourse: relatedCourse.value.trim(),
      teacherName: userInfo.userInfo.userName, // 从用户store获取
      contentResourcePath: fileUrls.length > 0 ? fileUrls.join(',') : '' // 多个文件URL用逗号分隔
    }

    console.log('提交数据:', submitData)

    // 4. 调用API提交
    showSuccessToast('正在发布教学帖子...')
    const response = await addTeachingPostUsingPost(submitData)

    if (response.data.code === 0) {

      resetForm()
      setTimeout(() => {
        showSuccessToast('发布成功！')
      },1000)
      router.push('/cqust/jsjl')
    } else {
      throw new Error(response.data.message || '发布失败')
    }
  } catch (error: any) {
    if (error.message !== 'cancel') {
      console.error('发布失败:', error)
      showFailToast(error.message || '发布过程中出错')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  talk_title.value = ''
  talk_nr.value = ''
  relatedCourse.value = ''
  fileList.value = []
  photoList.value = []
}

function go_back() {
  router.push("/cqust/jsjl")
}
</script>

<style scoped>
.addtalk {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.achievement-container {
  height: 100vh;
  overflow-y: auto;
  padding: 10px;
}
.top-title {
  height: 40px;
  background-color: #f8f8f8;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
}
.top_left{
  display: inline-block;
}
.top_second{
  display: inline-block;
  margin-left: 20px;
}
.top_right{
  line-height: 30px;
  display: inline-block;
  float: right;
}
.submit_button{
  background-color: #682757;
  color: #f9f9f9;
  border-radius: 60px;
  width: 70px;
  height: 35px;
  border: none;
}
.addtalk_nr_big{
  margin-bottom: 60px;
}
.upload-section {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 15px;
}

.upload-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.uploader {
  margin-top: 8px;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px;
  font-size: 12px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
}

.upload-status {
  text-align: center;
  padding: 2px;
  border-radius: 4px;
  margin: 2px;
}

.upload-status.uploading {
  background-color: #1989fa;
}

.upload-status.failed {
  background-color: #ee0a24;
}
</style>